package com.ddone.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ddone.helper.MenuHelper;
import com.ddone.helper.RouterHelper;
import com.ddone.mapper.SysMenuMapper;
import com.ddone.mapper.SysUserMapper;
import com.ddone.model.auth.SysMenu;
import com.ddone.model.auth.SysUser;
import com.ddone.model.vo.RouterVo;
import com.ddone.model.vo.SysUserQueryVo;
import com.ddone.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ddone
 * @date 2024/3/29-10:22
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    public Page<SysUser> queryPage(Page<SysUser> pageParam, SysUserQueryVo vo) {
        String keyword = vo.getKeyword();
        String beginTime = vo.getCreateTimeBegin();
        String endTime = vo.getCreateTimeEnd();
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(keyword), SysUser::getUsername, keyword)
                .or()
                .like(StringUtils.isNotBlank(keyword), SysUser::getName, keyword)
                .or()
                .like(StringUtils.isNotBlank(keyword), SysUser::getPhone, keyword)
                .and(StringUtils.isNotBlank(beginTime), wrapper -> wrapper.ge(SysUser::getCreateTime, beginTime))
                .and(StringUtils.isNotBlank(endTime), wrapper -> wrapper.le(SysUser::getUpdateTime, endTime));
        // return sysUserMapper.queryPage(pageParam,vo);
        return sysUserMapper.selectPage(pageParam, queryWrapper);
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        //创建SysUser对象
        SysUser sysUser = new SysUser();
        //设置id
        sysUser.setId(id);
        //设置用户状态
        sysUser.setStatus(status);
        //调用SysUserMapper中更新的方法
        sysUserMapper.updateById(sysUser);
    }

    @Override
    public SysUser getByUsername(String username) {
        return sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username));
    }

    @Override
    public Map<String, Object> getUserInfoByUserId(Long userId) {
        //创建一个Map
        Map<String, Object> map = new HashMap<>();

        // 获取用户信息
        SysUser user = sysUserMapper.selectById(userId);

        // 获取用户用户的菜单信息
        List<SysMenu> userMenuList = getUsersMenuByUserId(userId);

        //将userMenuList转换为菜单树
        List<SysMenu> userMenuTree = MenuHelper.buildTree(userMenuList);

        //将菜单树转换为路由
        List<RouterVo> routerVoList = RouterHelper.buildRouters(userMenuTree);

        //获取用户的按钮权限标识符 bnt.sysUser.list
        List<String> buttonPermissions = getUserBtnPermsByUserId(userId);

        //设置前端需要的数据，
        // {"code":200,"data":{
        // "roles":["admin"],
        // "introduction":"I am a super administrator",
        // "avatar":"https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
        // "name":"Super Admin"}}
        map.put("name",user.getName());
        //当前权限控制使用不到，我们暂时忽略
        map.put("roles",new HashSet<>());
        map.put("avatar","https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        map.put("routers", routerVoList);
        map.put("buttons", buttonPermissions);
        return map;
    }

    @Override
    public List<String> getUserBtnPermsByUserId(Long userId) {
        //调用根据用户id获取权限菜单的方法
        List<SysMenu> userMenuList = getUsersMenuByUserId(userId);
        //创建一个保存用户按钮权限标识的List
        return userMenuList.stream()
                .filter(sysMenu -> sysMenu.getType() == 2)
                // 将SysMenu的type值为2的perms的值放到buttonPermissons中
                .map(SysMenu::getPerms)
                .collect(Collectors.toList());
    }

    private List<SysMenu> getUsersMenuByUserId(Long userId) {
        List<SysMenu> userMenuList = null;
        //判断该用户是否是系统管理员
        if (userId == 1L) {
            //证明是系统管理员
            userMenuList = sysMenuMapper.selectList(new LambdaQueryWrapper<SysMenu>()
                    .eq(SysMenu::getStatus, 1)
                    .orderByAsc(SysMenu::getSortValue)
            );
        } else {
            //根据用户id查询用户的权限菜单
            userMenuList = sysMenuMapper.selectMenuListByUserId(userId);
        }
        return userMenuList;
    }
}
